# coding=utf-8
#

import os
import time

from django.core.management.base import BaseCommand

from huaweicloudsdkcore.auth.credentials import BasicCredentials
from huaweicloudsdkecs.v2.region.ecs_region import EcsRegion
from huaweicloudsdkcore.exceptions import exceptions
from huaweicloudsdkecs.v2 import *

from iminer.utils import check_pid

from iminer.tidal.models import TidalAgent


HW_API_AK = "HMBKL8CG3TWEGQSDYR2G"
HW_API_SK = "53nK542IfRwRUDBLvBvQQbwBacKkPRZXrnoruYcm"


class Command(BaseCommand):
    help = "定时遍历agent，发现异常agent"

    def handle(self, *args, **options):
        """ 定时遍历agent，发现异常agent """
        task_name = "pid/daily_delete_hw_agent"

        try:
            old_pid = int(open(task_name).read())
        except FileNotFoundError:
            old_pid = 0
        except ValueError:
            old_pid = 0

        cur_pid = os.getpid()
        if not old_pid or not check_pid(old_pid):
            with open(task_name, "w") as fp:
                fp.write(str(cur_pid))

            project_az_list = [{"project_id": "cf300e293b824ea7966711efd01c79dd", "az": "cn-east-3", "cn_name": "华东-上海一"},
                               {"project_id": "dcf3b3b06e5a48af9c2ae988d9488e3e", "az": "cn-south-1", "cn_name": "华南-广州"},
                               {"project_id": "e5b20769b4904199a176d05eefde87c5", "az": "cn-north-4", "cn_name": "华北-北京四"},
                               {"project_id": "ac2364344e244960b564f29013f115d8", "az": "cn-north-9", "cn_name": "华北-乌兰察布一"}]

            hold_servers = ["42b55ef0-7d60-44ab-8094-cbfa63eaaa4d", # 抢机器的实例
                    ]

            for i in range(3):

                for project_az_info in project_az_list:
                    server_list = []

                    project_id = project_az_info["project_id"]
                    az = project_az_info["az"]
                    cn_name = project_az_info["cn_name"]

                    print(project_id, az, cn_name)

                    server_list = [x.instance_id for x in TidalAgent.objects.filter(idc="huawei", endpoint=project_id, zone=az)]

                    credentials = BasicCredentials(HW_API_AK, HW_API_SK, project_id)
                    client = EcsClient.new_builder().with_credentials(credentials).with_region(EcsRegion.value_of(az)).build()

                    per_group = 50
                    for instance_list in [server_list[i:i+per_group] for i in range(0, len(server_list), per_group)]:
                        listServersbody = [ServerId(id=x) for x in instance_list]
                        request = DeleteServersRequest()
                        request.body = DeleteServersRequestBody(servers=listServersbody, delete_volume=True, delete_publicip=True)
                        response = client.delete_servers(request)
                        print(response)

                        if az == "cn-north-9":
                            time.sleep(3.14)

                time.sleep(55)
